package com.epfresh.supplier.activity.employ;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.CustomDialog;
import com.epfresh.api.utils.InputControl;
import com.epfresh.api.utils.T;
import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.AuthEntity;
import com.epfresh.supplier.entity.EmployEntity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by shenjie on 2017/9/15.
 */

public class EditEmployActivity extends BaseActivity {
    private RelativeLayout setAuth,delete;
    private EditText name,phone;
    private EmployEntity entity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Constant.posLists=null;
        Constant.wholeSaleLists=null;
        Constant.resources=null;
        initView();
        loadResourcesHttp();
    }

    private void initView(){
        toolbarTitle.setText("编辑员工");
        toolbarTitle.setTextColor(getResources().getColor(R.color.font_color_def));
        float textsize = getResources().getDimension(R.dimen.text_size_max_18);
        final float scale = getResources().getDisplayMetrics().density;
        float size = (textsize / scale + 0.5f);
//        toolbarTitle.setTextSize(size);
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);
        rightbtn.setVisibility(View.VISIBLE);
        rightbtn.setText("保存");
//        rightbtn.setTextSize( getResources().getDimension(R.dimen.text_size_mid_16)/scale + 0.5f);
        rightbtn.setTextColor(getResources().getColor(R.color.red));

        rightbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(InputControl.isEmpty(name)){
                    T.toast("请输入员工姓名");
                    return;
                }
                if(name.getText().toString().trim().length()>10){
                    T.toast("姓名长度不能超过10");
                    return;
                }
                loadHttp();
            }
        });
        setContentView(R.layout.activity_edit_employ);


        entity= (EmployEntity) getIntent().getSerializableExtra("entity");

        name= (EditText) findViewById(R.id.name_et);
        name.setText(entity.getName());
        phone= (EditText) findViewById(R.id.phone_et);
        phone.setText(entity.getPhone());
        setAuth= (RelativeLayout) findViewById(R.id.setauth);
        setAuth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(EditEmployActivity.this,AuthSettingActivity.class);
                intent.putExtra("isEdit",true);
                startActivity(intent);
            }
        });

        delete= (RelativeLayout) findViewById(R.id.delete_container);
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCustomDialog();
            }
        });

    }


    private void loadHttp(){
        if(!hasGetResource){
            T.toast("获取权限失败，请退出重新进入当前页面");
        }
        RequestEntitySupply<Map<String, Object>> data = new RequestEntitySupply<>();
        data.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_employee_modify);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, Object> map = new HashMap<>();
        map.put("id",entity.getId());
        map.put("name",name.getText().toString().trim());
        HashMap<String,Boolean> resources=new HashMap<>();
        if(Constant.posLists!=null){
            for (AuthEntity entity:Constant.posLists){
                if(entity.getMenu()==2&&entity.isHasAuth()){
                    resources.put(entity.getId(),Boolean.TRUE);
                }
            }
        }
        if(Constant.wholeSaleLists!=null){
            for (AuthEntity entity:Constant.wholeSaleLists){
                if(entity.getMenu()==2&&entity.isHasAuth()){
                    resources.put(entity.getId(),Boolean.TRUE);
                }
            }
        }
        if(Constant.posLists==null&&Constant.wholeSaleLists==null){
            Iterator iterator=Constant.resources.keys();
            while (iterator.hasNext()){
                String key= (String) iterator.next();
               resources.put(key,true);
            }
        }
        map.put("resources",resources);

        data.setParameters(map);
        request(data, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_employee_modify, onRequestListener);
    }


    private OnRequestListener<String> onRequestListener = new OnRequestListener<String>() {
        @Override
        public String jsonToObj(String responseStr) {
            return responseStr;
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<String> response, Object tag) {
            hideProgressDialog();
            T.toast("修改成功");
            setResult(100);
            finish();
        }
    };

    private void showCustomDialog(){
        CustomDialog.Builder builder=new CustomDialog.Builder(this);
        builder.setMessage("确认删除").setPositiveButton("删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                loadDeleteHttp();
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).create().show();

    }


    private OnRequestListener<String> deleteListener = new OnRequestListener<String>() {
        @Override
        public String jsonToObj(String responseStr) {
            return responseStr;
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<String> response, Object tag) {
            hideProgressDialog();
            T.toast("删除成功");
            setResult(100);
            finish();
        }
    };

    private void loadDeleteHttp(){
        RequestEntitySupply<Map<String, Object>> data = new RequestEntitySupply<>();
        data.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_employee_delete);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, Object> map = new HashMap<>();

        map.put("id",entity.getId());
        data.setParameters(map);
        request(data, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_employee_delete, deleteListener);
    }


    private boolean hasGetResource;
    private OnRequestListener<String> resourcesListener = new OnRequestListener<String>() {
        @Override
        public String jsonToObj(String responseStr) {
            return responseStr;
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<String> response, Object tag) {
            hideProgressDialog();
            String ss=response.getResponseElement();
            hasGetResource=true;
            try {
                Constant.resources=new JSONObject(ss);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    private void loadResourcesHttp(){
        RequestEntitySupply<Map<String, Object>> data = new RequestEntitySupply<>();
        data.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_employee_resources);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, Object> map = new HashMap<>();

        map.put("merchantId",entity.getMerchant_id());
        map.put("accountId",entity.getAccount_id());

        data.setParameters(map);
        request(data, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_employee_resources, resourcesListener);
    }


}
